"""
配置文件读取
"""
from pandas import read_excel
from os import path
from subprocess import check_output, CalledProcessError
from platform import system

# HIVE库
HIVE_DB = ''

# MySQL库
MYSQL_DB_ANALY_ = 'analy_'
MYSQL_DB_DATA_MANAGEMENT = 'data_management'

# 配置文件相对路径
MYSQL_PROD105_ROOT_PROPERTIES = 'mysql/prod105/root.properties'
XLSX = '数据同步.xlsx'

# 生产环境配置文件路径前缀
BASE_PATH_HDFS = '/config/'

# 本地文件路径
base_path = path.dirname(__file__)
xlsx = path.join(base_path, XLSX)


def read_xlsx():
    df = read_excel(xlsx, sheet_name=0)
    return df[df['服役'] == 1]


def read_xlsx_mysql():
    df = read_xlsx()
    return df[df['源类型'] == 'MySQL']  # 行筛选


def _properties2dict(properties: str) -> dict:
    """properties文件内容解析"""
    dt = dict()
    for r in properties.strip().split('\n'):
        if (not r.startswith('#')) and (r.find('=') > 0):
            k, v = r.split('=', 1)
            dt[k.strip()] = v.strip()
    return dt


def _cat_hdfs_properties(file_path) -> dict:
    """从HDFS读取配置文件，并获取参数"""
    cmd = 'hadoop fs -cat ' + file_path
    try:
        return _properties2dict(check_output(cmd, shell=True).decode().strip())
    except CalledProcessError:
        print('HDFS文件不存在')
        return dict()


def _read_local_properties(file_path) -> dict:
    """从本地读取配置文件，并获取参数"""
    try:
        with open(file_path) as f:
            return _properties2dict(f.read())
    except IOError:
        print('本地配置文件不存在')
        return dict()


def get_properties(file_path) -> dict:
    """读取配置文件，并获取参数"""
    if system() == 'Linux':
        hdfs_file_path = BASE_PATH_HDFS + file_path
        return _cat_hdfs_properties(hdfs_file_path)
    else:
        local_file_path = path.join(base_path, file_path)
        return _read_local_properties(local_file_path)


if __name__ == '__main__':
    print(read_xlsx())
    print(read_xlsx_mysql())
    print(get_properties(MYSQL_PROD105_ROOT_PROPERTIES))
